package com.example.controller;

import com.example.service.RaftServerListener;
import org.jgroups.Address;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

/**
 * @className: RaftServerController
 * @author: chentao
 * @date: 2025/9/18 8:55
 * @Version: 1.0
 * @description:
 */
@RestController
public class RaftServerController {

    @Resource
    private RaftServerListener raftServerListener;

    @GetMapping("/getServers")
    public List<Address> getServers() {
        return raftServerListener.getRaftServer().getServers();
    }

    @RequestMapping("/sendAll")
    public String sendAll() throws Exception {
        String uuid = UUID.randomUUID().toString();
        raftServerListener.getRaftServer().sendAll(uuid);
        return uuid;
    }

    @RequestMapping("/getLeader")
    public void getLeader(HttpServletResponse response) throws Exception {
        Address leader = raftServerListener.getRaftServer().getLeader();
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().write(leader.toString());
        response.getWriter().flush();
        response.getWriter().close();
    }
}
